﻿#include "IO/FileWriter.h"

#include <qdebug.h>

FileData::FileData()
{}

FileData::FileData(QString filePath, QByteArray data, QFile::OpenModeFlag openModeFlag)
{
	this->filePath = filePath;
	this->data = data;
	this->openModeFlag = openModeFlag;
}

FileData::~FileData()
{}

QString FileData::getFilePath()
{
	return filePath;
}

void FileData::setFilePath(QString& filePath)
{
	this->filePath = filePath;
}

QByteArray FileData::getData()
{
	return data;
}

void FileData::setData(QByteArray& data)
{
	this->data = data;
}

QFile::OpenModeFlag FileData::getOpenModeFlag()
{
	return openModeFlag;
}

void FileData::setOpenModeFlag(QFile::OpenModeFlag openModeFlag)
{
	this->openModeFlag = openModeFlag;
}

FileWriter::FileWriter(QObject* parent) :QThread(parent)
{
	isStart = true;
	start();
}

FileWriter::~FileWriter()
{
	isStart = false;
}

void FileWriter::saveAsFileNoWait(QString filePath, QByteArray data, SaveFileMode saveFileMode)
{
	FileData* fileData = new FileData(filePath, data, getOpenMode(saveFileMode));
	dataQueue.writeData(fileData);
}

bool FileWriter::saveAsFile(QString filePath, QByteArray data, SaveFileMode saveFileMode)
{
	return _saveAsFile(filePath, data, getOpenMode(saveFileMode));
}

bool FileWriter::_saveAsFile(QString filePath, QByteArray data, QFile::OpenModeFlag openModeFlag)
{
	QFile file(filePath);//建立文件对象
	if (!file.open(openModeFlag))//目标文件打开失败则返回false
	{
		return false;
	}
	file.write(data);//写入数据
	file.flush();
	file.close();//关闭文件
	return true;
}

void FileWriter::run()
{
	//文件存储线程保持持续运行
	while (true)
	{
		if (!isStart)
		{
			break;
		}
		FileData* fileData = dataQueue.readData();//从任务队列取出第一个任务对象，如果任务队列为空，则阻塞在此处
		_saveAsFile(fileData->getFilePath(), fileData->getData(), fileData->getOpenModeFlag());
		delete fileData;//删除任务对象
	}
}

